package com.example.demo.web.filter;

import com.example.demo.constants.Constants;
import com.example.demo.util.TraceUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.CommonsRequestLoggingFilter;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局日志打印，要最先执行，以方便记录所有
 * <p>
 * 有些过滤器执行较早，为保证最先执行，请设置Ordered.HIGHEST_PRECEDENCE
 *
 * @author hao.chen
 * @date 2023/5/30 10:15
 */
@Component
//@Order(Ordered.HIGHEST_PRECEDENCE + 10)
public class RequestLogFilter extends CommonsRequestLoggingFilter {


    public RequestLogFilter() {
        super.setIncludeClientInfo(true);
        super.setIncludeQueryString(true);
    }

    @Override
    protected boolean shouldLog(HttpServletRequest request) {
        return true;
    }

    @Override
    protected void beforeRequest(HttpServletRequest request, String message) {
        TraceUtil.putTraceIdToMdc();
        // 存入请求属性，而非ThreadContext 无需清除请求属性（请求对象生命周期随请求结束）
        // 当请求一个不存在的地址时，Spring MVC 的处理流程会发生变化 过滤器提前执行afterRequest
        request.setAttribute(Constants.BEGIN_TIME, System.currentTimeMillis());
        logger.info(message);
    }

    @Override
    protected void afterRequest(HttpServletRequest request, String message) {
        //logger.info(message);
        TraceUtil.removeTraceIdFromMdc();
    }

}
